package com.apexsoft.monitor.front.console.magent.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apexsoft.front.common.config.CommonConfig;
import com.apexsoft.front.common.utils.Md5Util;
import com.apexsoft.monitor.front.console.host.om.Host;
import com.apexsoft.monitor.front.console.magent.om.MonitorMagent;
import com.apexsoft.monitor.front.console.magent.om.Observer;


public class MagentThread extends Thread implements Observer{

    //监控几秒执行一次
    private long sleepTime = 3000;
    //监控的主机对象
    private Host host;

    /**
     * 监控程序状态和信息
     * @return
     */
    private JSONObject magentInfo;

    /**
     * 本现程是否一直运行
     * @return
     */
    private boolean runStatus = true;

    public String getHostId(){
        return java.lang.String.valueOf(this.host.getId());
    }

    //获取主机说明
    public String getHostShow(){
        return this.host.getHostName()+"("+this.host.getHostIp()+":"+this.host.getAgentPort()+")";
    }

    // 通过构造方法给线程名字赋值
    public MagentThread(Host host) {
        super(host.getHostName());// 给线程名字赋值
        this.host = host;
    }

    @Override
    public void run() {
        while(runStatus){
            MonitorMagent monitorMagent = new MonitorMagent(this.host);
            this.magentInfo = monitorMagent.getMagentInfo();
            try {
                sleep(sleepTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String getObserverId() {
        return this.getHostId();
    }

    @Override
    public void shutdownObserver() {
        this.runStatus = false;
        MonitorMagent monitorMagent = new MonitorMagent(this.host);
        monitorMagent.shutdowMagent();
    }

    @Override
    public boolean updateObserver(Host host) {
        String oldHostMd5 = Md5Util.encryption(JSON.toJSONString(this.host));
        String newHostMd5 = Md5Util.encryption(JSON.toJSONString(host));
        if(oldHostMd5!=null && !oldHostMd5.equals(newHostMd5)){
           this.shutdownObserver();
           return true;
        }
        if(this.magentInfo!=null && this.magentInfo.getDouble("magentVersion")!=null && this.magentInfo.getDoubleValue("magentVersion")<CommonConfig.getDouble("MAGENT.VERSION")){
            this.shutdownObserver();
            return true;
        }
        return false;
    }

    public Host getHost() {
        return host;
    }

    public JSONObject getMagentInfo() {
        return magentInfo;
    }
}
